<template>
  <div>
    <MainContent title="邮箱配置">
      <template #search-bar>
        <SearchBar inline>
          <template #toolbar>
            <el-form-item>
              <el-button type="primary" icon="Plus" @click="addEmail"
                >新增</el-button
              >
            </el-form-item>
          </template>
        </SearchBar>
      </template>
      <el-table :data="state.tableData" stripe v-loading="state.isLoading">
        <el-table-column prop="account" label="发件人账号" min-width="180" />
        <el-table-column prop="nickName" label="发件人昵称" min-width="100" />
        <el-table-column prop="host" label="邮件服务器" min-width="100" />
        <el-table-column prop="port" label="端口" min-width="120" />
        <el-table-column prop="defaultFlag" label="是否默认" min-width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.defaultFlag"
              class="ml-2"
              :active-value="1"
              :inactive-value="0"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button type="text" size="small" @click="editForm(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="updateStatus(scope.row.id)"
              >设为默认</el-button
            >
            <el-button type="text" size="small" @click="delEmail(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </MainContent>
    <el-dialog
      class="dialog-form"
      v-model="dialogFormVisible"
      :title="title"
      width="50%"
      :before-close="resetForm"
    >
      <el-form :model="form" ref="emailForm" :rules="rules" label-width="100px">
        <el-form-item label="发件人账号" prop="account">
          <el-input
            v-model="form.account"
            autocomplete="off"
            placeholder="发件人账号"
            maxlength="60"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            autocomplete="off"
            placeholder="密码"
            maxlength="60"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="发件人昵称">
          <el-input
            v-model="form.nickName"
            autocomplete="off"
            placeholder="发件人昵称"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="邮件服务器" prop="host">
          <el-input
            v-model="form.host"
            autocomplete="off"
            placeholder="邮件服务器"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input
            v-model="form.port"
            autocomplete="off"
            type="number"
            placeholder="请输入数字"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="是否为默认" prop="defaultFlag">
          <el-switch
            v-model="form.defaultFlag"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm(emailForm, edit)"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from "vue";
import {
  getEmailConfig,
  saveEmailConfig,
  saveEmailConfigDefault,
  delEmailConfig,
} from "@/api/system";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
// filterTemplate,
const router = useRouter();
const route = useRoute();
const state = reactive({
  isLoading: false,
  tableData: [] as Array<any>,
});
let form = ref({
  id: "",
  account: "",
  password: "",
  host: "",
  nickName: "",
  port: "",
  defaultFlag: 0,
});
const emailForm = ref<FormInstance>();
let edit = ref(false);
const rules = reactive({
  account: [
    {
      required: true,
      message: "请输入发件人账号",
      trigger: "blur",
    },
  ],
  nickName: [
    {
      required: true,
      message: "发件人昵称",
      trigger: "blur",
    },
  ],
  host: [
    {
      required: true,
      message: "请输入邮件服务器",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
  port: [
    {
      required: true,
      message: "请输入端口",
      trigger: "blur",
    },
  ],
  defaultFlag: [
    {
      required: true,
      message: "请选择是否默认",
      trigger: "blur",
    },
  ],
});
const dialogFormVisible = ref(false);

let title = ref("新增邮箱");

const addEmail = () => {
  title.value = "新建邮箱";
  edit.value = false;
  dialogFormVisible.value = true;
};
const getEmailPageList = async (): Promise<void> => {
  state.isLoading = true;
  const rs: any = await getEmailConfig();
  if (rs.code == 200) {
    state.tableData = rs.payload;
  }
  state.isLoading = false;
};
const editForm = async (val: any): Promise<void> => {
  Object.assign(form.value, {
    ...val,
  });
  title.value = "编辑邮箱";
  edit.value = true;
  dialogFormVisible.value = true;
};
const submitForm = (formEl: FormInstance | undefined, edit: any) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const rs: any = await saveEmailConfig(form.value);
      if (rs.code == 200) {
        resetForm();
        getEmailPageList();
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const resetForm = () => {
  form.value = {
    id: "",
    account: "",
    password: "",
    host: "",
    nickName: "",
    port: "",
    defaultFlag: 0,
  };
  emailForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const updateStatus = async (id: string | number) => {
  ElMessageBox.confirm("确定设置为默认邮箱吗", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs: any = await saveEmailConfigDefault({
        id: id,
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "设置成功",
        });
        getEmailPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};

const delEmail = (id: string | number) => {
  ElMessageBox.confirm("是否确定删除邮箱", "确认提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs: any = await delEmailConfig({
        id: id,
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getEmailPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
onMounted(() => {
  getEmailPageList();
});
</script>
<style lang="scss" scoped>
:deep(.el-form) {
  text-align: left;
  margin-top: 18px;
}

:deep(.el-table) {
  margin: 0 auto;
}
.page {
  margin: 10px auto;
}
.dialog-form {
  :deep(.el-date-editor) {
    width: 100%;
  }
}
:deep(.el-radio-group) {
  display: block;
}
:deep(.el-radio) {
  display: block;
}
.intro {
  display: inline-block;
  margin-left: 30px;
}
</style>
